package com.example.myapplication;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;
import org.json.JSONObject;

public class MainActivity2 extends AppCompatActivity {

    private static final String TAG = "MainActivity2";

    private ImageView avatarImage;
    private TextView usernameText;
    private TextView accountText;
    private TextView emailText;

    private MediaProjection mediaProjection; // 用于判断屏幕录制权限
    private ActivityResultLauncher<Intent> screenCaptureLauncher;

    private HandleWebSocket handleWebSocket;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        handleWebSocket = new HandleWebSocket(this);
        initViews();
        displayUserInfo();
        setupScreenCaptureLauncher();
        setupButtons();
        updatePermissionButtons();
    }

    private void initViews() {
        avatarImage = findViewById(R.id.avatarImage);
        usernameText = findViewById(R.id.usernameText);
        accountText = findViewById(R.id.accountText);
        emailText = findViewById(R.id.emailText);
    }

    @SuppressLint("SetTextI18n")
    private void displayUserInfo() {
        try {
            String userInfoJson = getIntent().getStringExtra("userInfo");
            if (userInfoJson != null) {
                JSONObject userJson = new JSONObject(userInfoJson);
                usernameText.setText("用户名: " + userJson.optString("realName"));
                accountText.setText("账号: " + userJson.optString("username"));
                emailText.setText("邮箱: " + userJson.optString("email"));

                String avatarUrl = userJson.optString("avatar");
                if (!avatarUrl.isEmpty()) {
                    Glide.with(this)
                            .load(avatarUrl)
                            .transition(DrawableTransitionOptions.withCrossFade())
                            .placeholder(R.drawable.app_logo)
                            .error(R.drawable.app_logo)
                            .circleCrop()
                            .into(avatarImage);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "用户信息解析失败", e);
            Toast.makeText(this, "用户信息解析失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void setupScreenCaptureLauncher() {
        screenCaptureLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
                        MediaProjectionManager manager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
                        mediaProjection = manager != null ? manager.getMediaProjection(result.getResultCode(), result.getData()) : null;
                        if (mediaProjection != null) {
                            Toast.makeText(this, "屏幕录制权限已授予", Toast.LENGTH_SHORT).show();
                            // 将 MediaProjection 提供给 WebSocket 使用
                            handleWebSocket.setMediaProjection(mediaProjection);
                        }
                    } else {
                        Toast.makeText(this, "屏幕录制权限被拒绝", Toast.LENGTH_SHORT).show();
                    }
                }
        );
    }


    private void setupButtons() {
        // 屏幕录制权限按钮
        findViewById(R.id.screenshotPermissionButton).setOnClickListener(v -> requestScreenCapturePermission());

        // 无障碍权限按钮

        findViewById(R.id.accessibilityPermissionButton).setOnClickListener(v ->
                PermissionHandler.requestAccessibilityPermission(this)
        );

        // 设备连接按钮
        MaterialButton button = findViewById(R.id.connectButton);

        button.setOnClickListener(v -> {
            TextInputEditText input = findViewById(R.id.deviceNameInput);
            String deviceName = input.getText() != null ? input.getText().toString().trim() : "";

            if (deviceName.isEmpty()) {
                Toast.makeText(this, "请输入设备名称", Toast.LENGTH_SHORT).show();
                return;
            }

            String btnText = button.getText().toString().trim();

            if (btnText.equals("连接服务")) {
                // 执行连接逻辑
                String token = getSharedPreferences("MyAppPrefs", MODE_PRIVATE)
                        .getString("accessToken", null);

                button.setEnabled(false);
                Toast.makeText(this, "正在连接设备：" + deviceName, Toast.LENGTH_SHORT).show();
                handleWebSocket.connectDevice(deviceName, button,token,() -> {
                    button.setText("断开连接");
                    button.setEnabled(true);
                });

            } else if (btnText.equals("断开连接")) {
                // 执行断开逻辑
                button.setEnabled(false);
                Toast.makeText(this, "正在断开设备：" + deviceName, Toast.LENGTH_SHORT).show();
                handleWebSocket.disconnectDevice(deviceName, button, () -> {
                    button.setText("连接服务"); // 断开完成后改为连接
                    button.setEnabled(true);
                });
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        updatePermissionButtons();
    }

    private void updatePermissionButtons() {
        Log.d(TAG, "更新权限按钮状态...");

        // 无障碍权限
        boolean isAccessibilityGranted = PermissionHandler.isAccessibilityPermissionGranted(this);
        findViewById(R.id.accessibilityPermissionButton).setVisibility(
                isAccessibilityGranted ? View.GONE : View.VISIBLE
        );
        findViewById(R.id.accessibilityPermissionGrantedIcon).setVisibility(
                isAccessibilityGranted ? View.VISIBLE : View.GONE
        );
        ((TextView) findViewById(R.id.accessibilityPermissionText)).setText(
                isAccessibilityGranted ? "无障碍权限已启用" : "无障碍权限未启用"
        );

        // 屏幕录制权限
        boolean isScreenCaptureGranted = mediaProjection != null;
        findViewById(R.id.screenshotPermissionButton).setVisibility(
                isScreenCaptureGranted ? View.GONE : View.VISIBLE
        );
        findViewById(R.id.screenshotPermissionGrantedIcon).setVisibility(
                isScreenCaptureGranted ? View.VISIBLE : View.GONE
        );
        ((TextView) findViewById(R.id.screenshotPermissionText)).setText(
                isScreenCaptureGranted ? "屏幕录制权限已启用" : "屏幕录制权限未启用"
        );
    }

    // 发起屏幕录制权限请求
    private void requestScreenCapturePermission() {
        MediaProjectionManager manager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        if (manager != null) screenCaptureLauncher.launch(manager.createScreenCaptureIntent());
    }
}
